﻿using Microsoft.AspNetCore.Mvc.Filters;
using MyWeb.Common.Helper;
using MyWeb.Model.User;
using MyWeb.Repository.UnitOfWorks;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.Extensions.ServiceExtensions.Filter
{
    public class ActionFilterAsync : IAsyncActionFilter
    {
        private readonly SqlSugarScope _dbBase;
        public ActionFilterAsync(IUnitOfWorkManage unitOfWorkManage)
        {
            _dbBase = unitOfWorkManage.GetDbClient();
        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string? fixedtoken = string.Empty;
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                fixedtoken = context.HttpContext.Request.Headers["Authorization"];
                fixedtoken = fixedtoken?.Replace("Bearer ", "");
            }
            else
            {
                fixedtoken = ((ClaimsIdentity)context.HttpContext.User.Identity)?.BootstrapContext?.ToString();
            }
            if (!(fixedtoken is null))
            {
                var TokenModel = JwtHelper.SerializeJwt(fixedtoken);


                var user = await _dbBase.Queryable<SysUserInfo>().Where(s => s.Id == TokenModel.Uid).FirstAsync();
                //将用户信息添加到请求头部
                context.HttpContext.Request.Headers.Add("UserInfo", JsonConvert.SerializeObject(user));

            }
            else
            {
                //throw new Exception("未获取到Token！");
            }
            await next();
        }
    }
}
